package com.yy.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
@Slf4j
public class MailUtil {
    @Value("${spring.mail.username}")
    private String sender; //邮件发送者

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private String port;
    @Value("${spring.mail.username}")
    private String username;

    /**
     * 发送纯文本邮件
     *
     * @param mail
     */
    public void sendSimpleMail(Mail mail) throws RuntimeException {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(sender); //邮件发送者
            mailMessage.setTo(mail.getRecipient()); // 邮件发给的人
            mailMessage.setSubject(mail.getSubject());  // 邮件主题
            mailMessage.setText(mail.getContent());  // 邮件内容

            javaMailSender.send(mailMessage);
            log.info("邮件发送成功 收件人：{}", mail.getRecipient());
        } catch (Exception e) {
            log.error("邮件发送失败 {}", e.getMessage());
            throw new RuntimeException("邮件发送异常"); //这是我自定义的一个异常码
        }
    }

    /**
     * 复杂邮件
     * 可附带各种文件的邮件
     *
     * @param mail
     */
//    public void sendWordMessageWord(Mail mail) throws MessagingException {
//        //复杂邮件
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        //true表示需要创建一个multipart message
//        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
//        messageHelper.setFrom(sender);
//        messageHelper.setTo(mail.getRecipient());
//        messageHelper.setSubject(mail.getSubject());
//        messageHelper.setText(mail.getContent());
//        String filePath = "E:\\demo\\个人简历.docx";
//        //这里需要给出文件的绝对路径
//        FileSystemResource file = new FileSystemResource(new File(filePath));
//        String fileName = file.getFilename();
//        messageHelper.addAttachment(fileName, file);
//
//        javaMailSender.send(mimeMessage);
//    }
}